#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Comm.hpp"
#include "Thread.hpp"

using namespace ThreadModule;

void Usage(char *argv[])
{
    std::cout << "Usage:\n\t" << argv[0] << " serverip serverport\n"
              << std::endl;
}

int InitClient(std::string &serverip, uint16_t serverport, struct sockaddr_in *serveraddr)
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if (sockfd < 0)
    {
        LOG(ERROR, "socket error");
        return -1;
    }

   // bzero(&serveraddr, sizeof(serveraddr));
    memset(serveraddr, 0, sizeof(struct sockaddr_in));
    serveraddr->sin_family = AF_INET;
    serveraddr->sin_port = htons(serverport);
    serveraddr->sin_addr.s_addr = inet_addr(serverip.c_str());

    return sockfd;
}

void recvmessage(int fd, std::string name)
{
    while (true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buf[1024];
        ssize_t ret = recvfrom(fd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&peer, &len);
        if (ret > 0)
        {
            buf[ret] = 0;
            fprintf(stderr, "[%s]%s\n", name.c_str(), buf);
        }
    }
}

void sendmessage(int fd, struct sockaddr_in &perror, std::string name)
{
    std::string message;
    while (true)
    {
        printf("%s | Eenter#", name.c_str());
        fflush(stdout);

        std::getline(std::cin, message);
        sendto(fd, message.c_str(), message.size(), 0, (struct sockaddr *)&perror, sizeof(perror));
    }
}

// 传输命令
int main(int argc, char *argv[])
{
    // 使用手册
    if (argc != 3)
    {
        Usage(argv);
        exit(1);
    }

    // 先拿到服务器ip再是端口号
    std::string serverip = argv[1];
    // 将字符串形式的端口号转换为整数
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in serveraddr;
    int sockfd = InitClient(serverip, serverport, &serveraddr);
    if (sockfd < 0)
        return -1;

    func_t r = std::bind(&recvmessage, sockfd, std::placeholders::_1);
    func_t s = std::bind(&sendmessage, sockfd, serveraddr, std::placeholders::_1);

    Thread Recver(r, "Recver");
    Thread Sender(s, "Sender");

    Recver.Start();
    Sender.Start();
    
    Recver.Join();
    Sender.Join();

    return 0;
}